package cn.neusoft.controller;

import cn.neusoft.po.Menu;
import cn.neusoft.po.Role;
import cn.neusoft.po.RoleMenu;
import cn.neusoft.po.RolePermission;
import cn.neusoft.query.RoleQuery;
import cn.neusoft.service.IRoleMenuService;
import cn.neusoft.service.IRolePermissionService;
import cn.neusoft.service.IRoleService;
import cn.neusoft.vo.ResponseObj;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hxj
 * @since 2023-12-19
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    IRoleService service;

    @PostMapping
    public ResponseObj saveOrUpdate(@RequestBody Role role){
        boolean b = service.saveOrUpdate(role);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(40001,"保存角色信息失败");
    }

    @DeleteMapping("/{id}")
    public ResponseObj delete(@PathVariable("id") Integer id){
        boolean b = service.removeById(id);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(40002,"删除角色信息失败");
    }

    @GetMapping("/{id}")
    public ResponseObj getById(@PathVariable("id") Integer id){
        Role role = service.getById(id);
        return ResponseObj.SUCCESS(role);
    }

    @PostMapping("/page")
    public ResponseObj getByPage(@RequestBody RoleQuery query){
        QueryWrapper queryWrapper = new QueryWrapper();
        if (query.getName()!=null){
            queryWrapper.like("name",query.getName());
        }
        Page pageQuery = new Page(query.getCurrent(),query.getSize());
        Page<Role> page = service.page(pageQuery, queryWrapper);
        return ResponseObj.SUCCESS(page);
    }

    @GetMapping("/all")
    public ResponseObj getAll(){
        List<Role> list = service.list();
        return ResponseObj.SUCCESS(list);
    }

    @Autowired
    IRoleMenuService roleMenuService;

    /**
     * 更新角色菜单
     * @param roleId
     * @param roleMenus
     * @return
     */
    @PostMapping("/changeRoleMenus/{roleId}")
    public ResponseObj changeRoleMenus(@PathVariable("roleId")Integer roleId, @RequestBody List<RoleMenu> roleMenus){
        boolean b = roleMenuService.changeRoleMenus(roleId, roleMenus);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(40003,"更新角色菜单失败");
    }

    @Autowired
    IRolePermissionService rolePermissionService;

    @PostMapping("/changeRolePermissions/{roleId}")
    public ResponseObj changeRolePermission(@PathVariable("roleId")Integer roleId, @RequestBody List<RolePermission> rolePermissions){
        boolean b = rolePermissionService.changeRolePermission(roleId, rolePermissions);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(40003,"更新角色权限失败");
    }
    
}
